package com.sam.sqlite;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.sam.data.DbDataUtil;
import com.sam.data.TimeUtils;
import com.sam.data.UserData;

import java.util.ArrayList;
import java.util.List;

/**
 * &lt;br&gt;Created
 *
 * @author wangds
 * @see
 */
public class UserDao {
    public final static String create_table = "create table if not exists " + UserData.TABLE_NAME + " ("
           +  "name VARCHAR  ,"
            +  "age INTEGER ,"
            +  "height REAL "
            + ")";

    SQLiteDatabase db;

    public UserDao(SQLiteDatabase db) {
        this.db = db;
    }

    public boolean saveList(){
        boolean result = true;
        DbDataUtil dbDataUtil = new DbDataUtil();
        ContentValues cv;
        TimeUtils.start();
        db.beginTransaction();
        for (UserData userData : dbDataUtil.list) {
            cv = new ContentValues();
            cv.put("name",userData.getName());
            cv.put("age", userData.getAge());
            cv.put("height", userData.getHeight());
           if( db.insert(UserData.TABLE_NAME,null,cv) == -1){
               result = false;
           }
        }
        db.setTransactionSuccessful();
        db.endTransaction();
        TimeUtils.end("SQLiteDatabase.saveList:");
        return result;
    }

    public List<UserData> query(){
        TimeUtils.start();
        List<UserData> list = new ArrayList<>();
        Cursor cursor = db.query(UserData.TABLE_NAME, null, null, null, null, null, null);
        UserData userData;
        while (cursor.moveToNext()){
            userData = new UserData();
            userData.setName(cursor.getString(0));
            userData.setAge(cursor.getInt(1));
            userData.setHeight(cursor.getFloat(2));
            list.add(userData);
        }
        TimeUtils.end("SQLITE.query");
        return list;
    }

}
